<?php


namespace app\common\library;

use common;
use think\Db;
use think\facade\Env;
use app\common\library\PlatformModel;
use think\facade\Log;

require_once Env::get('extend_path').'/Wxpay/WxPay.Api.php';


class WxpayMoldel
{
    var $_wxpay = null;

    function __construct($city_id = null)
    {
        if (empty($city_id)){
            $this->_wxpay = config('app.wxpay');
        }
        else{
            $vxkcfg = PlatformModel::get_city_al_token($city_id);
            $this->_wxpay = $vxkcfg['wxpay'];
        }

    }

    function wx_sign($data)
    {
        ksort($data);

        $sarr = [];
        foreach ($data as $k => $v) {
            $sarr[] = "$k=$v";
        }
        $sarr[] = "key={$this->_wxpay['key']}";

        $s = implode('&', $sarr);
        Log::debug("wxsign =================== ".$s);
        return strtoupper(md5($s));
    }

    function create_wxmp_unifield_order($userinfo,$pay_id, $amount, $body,$pay_city,$profit_sharing)
    {
        $out_trade_no = $pay_id;

        $total_fee = $amount;
        $platform = (new PlatformModel())->get_platform_info('wxmpu');
        WxPayConfig::$NOTIFY_URL = $this->_wxpay['notify_url'];
        WxPayConfig::$APPID = $platform['appid'];
        WxPayConfig::$KEY = $this->_wxpay['key'];
        WxPayConfig::$MCHID = $this->_wxpay['mch_id'];
        WxPayConfig::$SSLCERT_PATH = $this->_wxpay['sslcert_path'];
        WxPayConfig::$SSLKEY_PATH = $this->_wxpay['sslkey_path'];

        $uo = new WxPayUnifiedOrder();
        $uo->SetBody($body);
        $uo->SetAttach($pay_city);
        $uo->SetOut_trade_no($out_trade_no);
        $uo->SetTotal_fee($total_fee);
        $uo->SetTrade_type('JSAPI');

        $uo->SetOpenid($userinfo['wxmp_open_id']);
        $uo->SetTrade_type('JSAPI');

        if ($profit_sharing){
            $uo->SetProfitSharing('Y');
        }


        $wxresult = WxPayApi::unifiedOrder($uo);
        if (empty($wxresult)) {
            return null;
        }
        $prepay_info = [
            'appId' => $platform['appid'],
            'package' => 'prepay_id=' . $wxresult['prepay_id'],
            'nonceStr' => uniqid(),
            'timeStamp' => time(),
            'signType' => 'MD5',
            'prepay_id' => $wxresult['prepay_id'],
        ];


        $sign = $this->wx_sign($prepay_info);
        $prepay_info['sign'] = $sign;
        $prepay_info['mch_id'] = $this->_wxpay['mch_id'];
        $prepay_info['prepay_id'] = $wxresult['prepay_id'];
        return $prepay_info;
    }

    function create_wxapp_unifield_order($userinfo,$pay_id, $amount, $body,$pay_city)
    {
        $out_trade_no = $pay_id;

        $total_fee = $amount;
        $platform = (new PlatformModel())->get_platform_info('wxapp');
        WxPayConfig::$NOTIFY_URL = $this->_wxpay['notify_url'];
        WxPayConfig::$APPID = $platform['appid'];
        WxPayConfig::$KEY = $this->_wxpay['key'];
        WxPayConfig::$MCHID = $this->_wxpay['mch_id'];
        WxPayConfig::$SSLCERT_PATH = $this->_wxpay['sslcert_path'];
        WxPayConfig::$SSLKEY_PATH = $this->_wxpay['sslkey_path'];

        $uo = new WxPayUnifiedOrder();
        $uo->SetAttach($pay_city);
        $uo->SetBody($body);
        $uo->SetOut_trade_no($out_trade_no);
        $uo->SetTotal_fee($total_fee);
        $uo->SetTrade_type('JSAPI');

        $uo->SetTrade_type('APP');

        $wxresult = WxPayApi::unifiedOrder($uo);
        if (empty($wxresult)) {
            return null;
        }
        $prepay_info = [
            'appid' => $platform['appid'],
            'package' => 'prepay_id=' . $wxresult['prepay_id'],
            'noncestr' => uniqid(),
            'timestamp' => time(),
            'prepayid' => $wxresult['prepay_id'],
            'partnerid' => $this->_wxpay['mch_id'],
        ];

        $sign = $this->wx_sign($prepay_info);
        $prepay_info['sign'] = $sign;
        $prepay_info['mch_id'] = $this->_wxpay['mch_id'];
        $prepay_info['prepay_id'] = $wxresult['prepay_id'];
        return $prepay_info;
    }


    function download_bill($date)
    {
        $date = str_replace('-', '', $date);
        $file_path = '/data/ebike/wxbill/' . 'wxmpu_' . $date;
        if (file_exists($file_path)) {
            return true;
        }

        $platform = (new PlatformModel())->get_platform_info('wxmpu');
        WxPayConfig::$NOTIFY_URL = $this->_wxpay['notify_url'];
        WxPayConfig::$APPID = $platform['appid'];
        WxPayConfig::$KEY = $this->_wxpay['key'];
        WxPayConfig::$MCHID = $this->_wxpay['mch_id'];
        WxPayConfig::$SSLCERT_PATH = $this->_wxpay['sslcert_path'];
        WxPayConfig::$SSLKEY_PATH = $this->_wxpay['sslkey_path'];

        $input = new WxPayDownloadBill();
        $date = trim($date, " -");
        $input->SetBill_date($date);
        $input->SetBill_type('ALL');
        $input->SetNonce_str(common::random_string(32));
        $resp = WxPayApi::downloadBill($input, 30);
        if (empty($resp)) {
            return false;
        }

        file_put_contents($file_path, $resp);
        $lines = explode(PHP_EOL, $resp);
        foreach ($lines as $line) {
            $arr = explode(',`', $line);
            if (!common::is_datetime(trim($arr[0], '`'))) {
                continue;
            }

            $data = [
                'create_time' => trim($arr[0], '`'),
                'appid' => trim($arr[1], '`'),
                'merch_id' => trim($arr[2], '`'),
                'devece_no' => trim($arr[4], '`'),
                'trade_no' => trim($arr[5], '`'),
                'out_trade_no' => trim($arr[6], '`'),
                'open_id' => trim($arr[7], '`'),
                'trade_type' => trim($arr[8], '`'),
                'result' => trim($arr[9], '`'),
                'bank_type' => trim($arr[10], '`'),
                'fee_type' => trim($arr[11], '`'),
                'total_fee' => intval(floatval(trim($arr[12], '`')) * 100),
                'refund_trade_no' => trim($arr[14], '`'),
                'out_refund_trade_no' => trim($arr[15], '`'),
                'refund_fee' => intval(floatval(trim($arr[16], '`')) * 100),
                'attach' => trim($arr[20], '`'),
            ];
            try {
                Db::table('tb_wxpay_order')->insert($data);
            } catch (Exception $ex) {
                Log::error("download wxpay bill".$ex->getMessage());
            }
        }
    }

    function query_info_by_out_trade_no($out_trade_no)
    {

        $selectlist = [
            'trade_no' => 'string',
            'out_trade_no' => 'string',
            'result' => 'string',
        ];
        $sfs = array_keys($selectlist);
        $beans = [
            'out_trade_no'=>$out_trade_no
        ];

        $rows = Db::table('tb_wxpay_order')->where($beans)->field($sfs)->find();
        if (empty($rows)) {
            return null;
        }
        return $rows;
    }

    function query_info_by_out_refund_trade_no($out_trade_no)
    {

        $selectlist = [
            'trade_no' => 'string',
            'out_trade_no' => 'string',
            'result' => 'string',
            'refund_trade_no' => 'string',
            'refund_out_trade_no' => 'string',
        ];
        $sfs = array_keys($selectlist);
        $beans = [
            'out_refund_trade'=>$out_trade_no
        ];


        $rows = Db::table('tb_wxpay_order')->where($beans)->field($sfs)->find();
        if (empty($rows)) {
            return null;
        }
        return $rows;
    }

    function query_count($date)
    {
        $ds = $date . " 00:00:00";
        $de = $date . " 23:59:59";
        $cdx = " create_time >= '{$ds}' and create_time <= '{$de}'";

        return Db::table('tb_wxpay_order')->where($cdx)->count();
    }


    //分账
    function create_wxprofitshare_order($order_id,$pay_id, $reveivers)
    {
        $platform = (new PlatformModel())->get_platform_info('wxmpu');
        WxPayConfig::$NOTIFY_URL = $this->_wxpay['notify_url'];
        WxPayConfig::$APPID = $platform['appid'];
        WxPayConfig::$KEY = $this->_wxpay['key'];
        WxPayConfig::$MCHID = $this->_wxpay['mch_id'];
        WxPayConfig::$SSLCERT_PATH = $this->_wxpay['sslcert_path'];
        WxPayConfig::$SSLKEY_PATH = $this->_wxpay['sslkey_path'];

        $out_trade_no = $pay_id;

        $uo = new WxPayProfitShare();
        $uo->SetAppid(WxPayConfig::$APPID);
        $uo->SetOut_trade_no($order_id);
        $uo->SetTransaction_id($out_trade_no);
        $uo->SetMch_id(WxPayConfig::$MCHID); //商户号
        $uo->SetNonce_str(WxPayApi::getNonceStr()); //随机字符串

        //receviers
        $arr = array();

        foreach ($reveivers as $val){
            $arr_val1 = [
                'type' => 'MERCHANT_ID',
                'account' => $val['account'],
                'amount'  => $val['amount'],
                'description' => $val['desc']
            ];
            array_push($arr,$arr_val1);
        }

        $uo->SetReceivers(json_encode($arr));

        $uo->SetProfitSign();

        $wxresult = WxPayApi::profit_share($uo);
        if (empty($wxresult)) {
            return null;
        }
        return $wxresult;
    }
}
